package com.rpc.demo.provider.rpc.server.handler;

import com.rpc.demo.common.model.Invocation;
import com.rpc.demo.common.util.ApplicationContextGetBeanHelper;
import com.rpc.demo.common.util.StringUtil;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.net.Socket;
import java.util.Map;

/**
 * @Author: ZhaoJie
 * @Date: 2022/4/6
 * @Description: 处理rpc请求，使用反射执行方法
 * @Modify: ===================================================
 * Modifier        Modifytime        Description
 * ===================================================
 */

public class ServerHandler implements Runnable{

    private Socket socket;
    private Map<String, Class> serviceMap;

    public ServerHandler(Socket socket, Map<String, Class> serviceMap) {
        this.serviceMap = serviceMap;
        this.socket = socket;
    }

    @Override
    public void run() {
        ObjectInputStream in = null;
        ObjectOutputStream out = null;
        try {
            in = new ObjectInputStream(socket.getInputStream());
            out = new ObjectOutputStream(socket.getOutputStream());

            //获取invocation对象
            Invocation invocation = (Invocation) in.readObject();

            // 通过class name来获取实例对象

            //执行对应方法
            String[] classPath = invocation.getInterfaceName().split("\\.");
            String classBeanName = classPath[classPath.length - 1];
            // 通过传过来的class 名字从beanfactory中获取对应的实例
            Class class1 = ApplicationContextGetBeanHelper.getBean(classBeanName);
            // 反射拿到方法
            Method method = class1.getMethod(invocation.getMethodName(), invocation.getParamTypes());
            // 反射得到结果
            Object invoke = method.invoke(class1.newInstance(), invocation.getParams());
            // 返回方法执行结果
            out.writeObject(invoke);
            out.flush();
        } catch (Exception exception) {
            exception.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            socket = null;
        }
    }
}
